package 极客算法训练营.chapter09;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class 在每个树行中找最大值 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    class Solution1 {
        public List<Integer> largestValues(TreeNode root) {
            //存储结果
            List<Integer> res = new ArrayList<>();
            //存储层级结点
            Deque<TreeNode> queue = new ArrayDeque<>();
            if (root == null) {
                return res;
            }
            queue.addLast(root);
            while (!queue.isEmpty()) {
                int max = Integer.MIN_VALUE;
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.pollFirst();
                    max = Math.max(max, node.val);
                    if (node.left != null) {
                        queue.addLast(node.left);
                    }
                    if (node.right != null) {
                        queue.addLast(node.right);
                    }
                }
                res.add(max);
            }
            return res;
        }
    }

    class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            dfs(0, root, res);
            return res;
        }

        public void dfs(int depth, TreeNode node, List<Integer> res) {
            if (node == null) {
                return;
            }
            if (depth >= res.size()) {//初次赋值
                res.add(node.val);
            } else if (node.val > res.get(depth)){//比较赋值
                res.set(depth, node.val);
            }
            dfs(depth + 1, node.left, res);
            dfs(depth + 1, node.right, res);
        }
    }
}
